<?php

namespace app\common\logic;

use app\common\exception\BusinessException;

class BuildEsQuestionFormat
{
    private $question;

    private $questionBackground;

    public function __construct($question, $questionBackground)
    {
        $this->question = $question;
        $this->questionBackground = $questionBackground;
    }

    public function build()
    {
        // 检查参数
        $this->check();

        // 返回文本
        $response = '';

        // 背景信息
        $response .= $this->buildBackground();

        // 标题信息
        $response .= $this->buildQuestionAsk();

        // 选项信息
        $response .= $this->buildQuestionOptions();

        // 答案信息
        $response .= $this->buildAnswer();

        // 解析信息
        $response .= $this->buildExplanation();

        // 返回
        return strip_tags($response);
    }

    private function buildExplanation()
    {
        if (empty($this->question['explanation'])) {
            return '';
        }
        $explanation = $this->question['explanation'] ?: '';
        return $explanation . ' ';
    }

    private function buildAnswer()
    {
        $correctOption = $this->question['correctOption'] ?: '';
        return $correctOption . ' ';
    }

    private function buildQuestionOptions()
    {
        $allOptions = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
        $allOptionText = [];
        foreach ($allOptions as $option) {
            $optionText = $this->question['answerOption'][$option] ?? '';
            if ($optionText) {
                $allOptionText[] = $option . ' ' . $optionText;
            }
        }
        if ($allOptionText) {
            return join(' ', $allOptionText) . ' ';
        }
        return '';
    }

    private function buildQuestionAsk()
    {
        return $this->question['questionAsk'] . ' ';
    }

    private function buildBackground()
    {
        if (!$this->questionBackground) {
            return '';
        }
        return $this->questionBackground . ' ';
    }


    /**
     * check
     * @throws BusinessException
     */
    public function check()
    {
        if (empty($this->question['questionAsk'])) {
            throw new BusinessException('题目标题不完整不支持生成');
        }
        if (empty($this->question['correctOption']) && empty($this->data['explanation'])) {
            throw new BusinessException('题目答案和题目解析同时为空不支持生成');
        }
    }
}